package com.jhf.youke.base.app.executor;

import com.jhf.youke.base.app.feign.WechatFeign;
import com.jhf.youke.base.domain.exception.UserException;
import com.jhf.youke.base.domain.model.dto.LoginDto;
import com.jhf.youke.base.domain.model.dto.VideoLoginDto;
import com.jhf.youke.base.domain.service.DigitalSignatureService;
import com.jhf.youke.base.domain.service.UserService;
import com.jhf.youke.core.entity.Response;
import com.jhf.youke.core.utils.Constant;
import com.jhf.youke.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


/**
 * @author RHJ
 */
@Slf4j
@Service
public class LoginAppService {

    @Resource
    private UserService userService;

    @Resource
    private DigitalSignatureService digitalSignatureService;

    @Resource
    private WechatFeign wechatFeign;


    public Map<String,Object> loginByPwd(LoginDto loginDto) throws Exception{
        String login = null;
        try {
            login = digitalSignatureService.verification(loginDto.getSign(), loginDto.getData(), loginDto.getNonceStr(), loginDto.getCompanyId());
        }catch (Exception e){
            log.info("login error {}", e.getMessage());
        }
        assert login != null: (new UserException("登录失败"));

        Map<String,Object> token = userService.loginByPwd(login);
        return token;
    }

    public Boolean logout(String token) {
        return userService.logout(token);
    }


    public Map<String,Object> loginByMobile(LoginDto loginDto) {
        String login = "";
        Map<String,Object> token = new HashMap<>(32);
        try {
            login = digitalSignatureService.verification(loginDto.getSign(), loginDto.getData(), loginDto.getNonceStr(), loginDto.getCompanyId());
        }catch (Exception e){
            token.put("code", Constant.CODE_SIGNATURE_EXCEPTION);
            return token;
        }
        if(StringUtils.isBlank(login)){
            token.put("code", Constant.CODE_NOT_REGISTERED);
            return token;
        }
        token = userService.loginByMobile(login);
        return token;
    }

    /**
     * 视频小程序登录
     * @param dto
     * @return
     */
    public Map<String,Object> videoLogin(VideoLoginDto dto) {
        Response<String> openIdData = wechatFeign.getOpenIdByCode(Map.of("code", dto.getCode()));
        if(openIdData == null || openIdData.getCode() != 0){
            throw new UserException("登录失败");
        }
        dto.setOpenid(openIdData.getData());
        Map<String,Object> data = userService.videoLogin(dto);
        if(data == null){
            return userService.videoRegister(dto);
        }else {
            return data;
        }
    }

}

